from app.account.models import UserInfo, UserLog
from common.authCheck.userAuth import check_login, getUser
from common.dictInfo import model_to_dict
from django.http import JsonResponse
from rest_framework.views import APIView
import json


class UserInfoView(APIView):
    COMMON_FIELD = [
        'nickname', 'signature', 'user_sex', 'join_date'
    ]
    EXCLUDE_USER_FIELDS = [
        'password', 'head_portrait'
    ]

    @check_login
    def get(self, request, uid=0):
        """
        获取用户信息
        :param request:
        :param uid:
        :return:
        """
        if uid == 0:
            # 查看自己的信息
            user = getUser(request.session.get('login'))
            self.COMMON_FIELD += ['email', 'realName']
        else:
            user = UserInfo.objects.filter(id=uid)
            if not user.exists():
                return JsonResponse({
                    'status': False,
                    'errMsg': '用户不存在'
                }, status=404)
            user = user[0]
        userLog = UserLog.objects.get(related_user=user)
        userDict = model_to_dict(user, fields=self.COMMON_FIELD)
        logDict = model_to_dict(userLog, exclude='related_user')
        for i in user.roles:
            # 用户身份标识
            if i[0] == user.user_role:
                userDict['role'] = i[1]
                break
        if user.head_portrait:
            userDict['head_portrait'] = user.head_portrait
        else:
            userDict['head_portrait'] = None
        return JsonResponse({
            'status': True,
            'user': userDict,
            'logCount': logDict
        })

    @check_login
    def put(self, request):
        """
        修改用户信息
        :param request:
        :return:
        """
        user = getUser(request.session.get('login'))
        jsonParams = json.loads((request.body).decode('utf-8'))
        user.email = jsonParams.get('email', user.email)
        user.nickname = jsonParams.get('nickname', user.nickname)
        user.user_sex = jsonParams.get('sex', user.user_sex)
        user.realName = jsonParams.get('realName', user.realName)
        user.save()
        userDict = model_to_dict(user, exclude=self.EXCLUDE_USER_FIELDS)
        return JsonResponse({
            'status': True,
            'user': userDict
        })

    @check_login
    def post(self, request):
        """
        修改密码(原密码)
        :param request:
        :return:
        """
        from django.contrib.auth.hashers import make_password, check_password
        user = getUser(request.session.get('login'))
        jsonParams = json.loads((request.body).decode('utf-8'))
        db_password = user.password.password
        if check_password(db_password, jsonParams.get('old_password')):
            newPassword = make_password(jsonParams.get('new_password'))
            user.password.password = newPassword
            user.password.save()
            return JsonResponse({
                'status': True,
                'id': user.id,
                'nickname': user.nickname
            })
        else:
            return JsonResponse({
                'status': False,
                'errMsg': '原密码错误'
            }, status=401)
